﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Threading;

namespace BaseHelper.Net
{
    public class TcpClientHelper
    {
        public delegate void DataArriveHandler(string remoteIP, byte[] buffer, int len);
        public event DataArriveHandler DataArriveEvent;

        public delegate void DisconnectHandler(string remoteIP);
        public event DisconnectHandler DisconnectEvent;

        public delegate void DebugHandler(string caption,string msg);
        public static event DebugHandler DebugEvent;

        private NetworkStream _ns;
        private TcpClient _tcpClient;

        private string _error;

        public string Error
        {
            set { _error = value; }
            get { return _error; }
        }

        public bool IsConnected
        {
            get { return _tcpClient != null && _tcpClient.Connected; }
        }

        private static void DebugLog(string caption, string msg)
        {
            try
            {
                if (DebugEvent != null)
                    DebugEvent(caption, msg);
            }
            catch { }
        }


        private static void DebugLog(string caption,byte[] buffer, int len)
        {
            try
            {
                if (DebugEvent != null)
                {
                    string str = BitConverter.ToString(buffer, 0, len).Replace("-", " ");
                    DebugEvent(caption, str);
                }
            }
            catch { }
        }


        public bool Connect(string IP, int Port, int bufferSize)
        {

            Close();

            _tcpClient = new TcpClient();
            try
            {
                _tcpClient.Connect(IPAddress.Parse(IP), Port);
                _tcpClient.ReceiveBufferSize = bufferSize;
                _tcpClient.SendBufferSize = bufferSize;
                _ns = _tcpClient.GetStream();
                Thread th = new Thread(new ThreadStart(DataArrived));
                th.Name = "BaseHelper.Net.TcpClientHelper.Connect()";
                th.Start();

                DebugLog("连接成功",IP+":"+Port.ToString());
                return true;
            }
            catch(Exception ex)
            {
                DebugLog("连接失败",IP+":"+Port.ToString() +"," + ex.Message);
            }

            return false;
        }

        public bool Bind(TcpClient client)
        {

            _tcpClient = client;
            string IP = client.Client.RemoteEndPoint.ToString();
            try
            {
                _ns = client.GetStream();
                Thread th = new Thread(new ThreadStart(DataArrived));
                th.Name = "BaseHelper.Net.TcpClientHelper.Connect()";
                th.Start();
                DebugLog("绑定成功", IP);
                return true;
            }
            catch(Exception ex)
            {
                DebugLog("绑定失败" ,IP  + "失败，" + ex.Message);
            } 
            return false;
        }

        private void DataArrived()
        {
            try
            {

                byte[] buffer = new byte[_tcpClient.ReceiveBufferSize];
                string remoteIP = _tcpClient.Client.RemoteEndPoint.ToString();
          
                try
                {
                    while (true)
                    {
                        int len = _ns.Read(buffer, 0, buffer.Length);
                        if (len == 0)
                            break;

                        if (DataArriveEvent != null)
                            DataArriveEvent(remoteIP, buffer, len);

                        DebugLog("接收数据 " + len.ToString(), buffer, len);
                    }
                }
                catch(Exception ex1)
                {
                    Console.WriteLine("BaseHelper.Net.TcpHelper.DataArread1()" + ex1.Message);
                }
                if (DisconnectEvent != null)
                    DisconnectEvent(remoteIP);

                DebugLog("断开连接", remoteIP);
            }
            catch(Exception ex)
            {
               // Console.WriteLine("BaseHelper.Net.TcpHelper.DataArread3()" + ex.Message);
            }
         

        }


        public bool SendBytes(byte[] buffer)
        {
            try
            {
                this.Error = "";
                if (_ns != null)
                {
                    _ns.Write(buffer, 0, buffer.Length);
                    _ns.Flush();

                    DebugLog("发送数据 " + buffer.Length.ToString(), buffer,buffer.Length);

                    return true;
                }

            }
            catch (Exception ex)
            {
                DebugLog("发送数据",ex.Message);
                this.Error = ex.Message;
                Console.WriteLine("BaseHelper.Net.TcpHelper.SendBytes()" + ex.Message);
            }

            return false;
        }


        public void Close()
        {
            try
            {
                if (_tcpClient != null)
                {
                    _tcpClient.Close();
                }
                DebugLog("关闭连接", "结束");

            }
            catch { }
        }


    }
}
